import {messages} from "share/common";
import React from 'react'

import { Form, Upload, Icon, message, Modal, Button } from 'antd'
const Dragger = Upload.Dragger;
import config from 'config'
import FileViewer from 'components/file-viewer'
import 'styles/components/image-upload.scss'

import {connect} from "react-redux";

/**
 * 图片上传组件
 *
 * 2018/11/26 zaranengap
 * 在系统组件中但是又不那么算是系统组件的东西
 * 很多字段定死了，默认值也是个业务接口
 * 系统组件不应该很纯粹吗，这么多业务字段是搞毛线啊
 * 但是很多定死的字段不是很正常吗
 * 很多库里的字段也是定死的啊
 * 这么一想我就不想动他了
 *
 */
class ImageUpload extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      result: [],
      previewIndex: 0, //预览图片的index
      imgIsUploading: false, //图片是否是正在上传的状态，用来解决 isShowDefault 为true时，上传过程中会出现显示两张图片的情况
    }
  }
  componentDidMount() {
    if (this.props.defaultFileList.length) {
     this.showDefaultFileList(this.props.defaultFileList);
    }
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.defaultFileList.length !== this.props.defaultFileList.length){
      this.showDefaultFileList(nextProps.defaultFileList);
    }
    if(nextProps.isShowDefault){
      if (nextProps.defaultFileList.splice && !this.state.imgIsUploading) {
        this.showDefaultFileList(nextProps.defaultFileList);
      }
    }
  }
  //为了显示默认已经上传的图片
  showDefaultFileList=(defaultFileList)=>{
    let fileList = [];
    defaultFileList.map(attachment => {
      fileList.push({
        uid: attachment.attachmentOID,
        attachmentOID: attachment.attachmentOID,
        name: attachment.fileName,
        fileName: attachment.fileName,
        fileURL: attachment.fileURL,
        status: 'done',
        url: attachment.fileURL
      })
    });
    this.setState({ fileList, result: defaultFileList })
  };

  handleData = () => {
    return {
      attachmentType: this.props.attachmentType
    };
  };


  handleChange = (info) => {
    if (this.props.fileType) {  //控制上传图片的类型
      if (this.props.isExpense) {

      } else {
        let isFileType = false;
        this.props.fileType.map(type => {
          info.file.type === `image/${type}` && (isFileType = true)
        });
        if (!isFileType && info.file.status !== 'removed') {
          //上传失败，图片格式错误
          message.error(messages('components.key398'/*上传失败，图片格式错误*/));
          return
        }
      }
    }
    if (this.props.fileSize) {  //控制上传图片的大小
      const isLtSize = info.file.size / 1024 / 1024 <= this.props.fileSize;
      if (!isLtSize && info.file.status !== 'removed') {
        //上传失败，图片应不大于 {total} M
        message.error(messages('components.key656',{arg1: this.props.fileSize}/*上传失败，图片应不大于 {arg1} M*/));
        return
      }
    }
    this.props.isUploading(true);
    this.setState({ imgIsUploading: true });
    let fileList = info.fileList;
    fileList.map(file => {
      if(file.thumbUrl)
        file.url = file.thumbUrl;
    });
    this.setState({ fileList },() => {
      const status = info.file.status;
      let { result } = this.state;
      if (status === 'done') {
        message.success(`${info.file.name} ${messages('components.key399'/*上传成功*/)}`);
        result.push(info.file.response);
        this.setState({ result, imgIsUploading: false },() => {
          this.props.isUploading(false);
          this.props.onChange(result);
        });
      } else if (status === 'error') {
        this.props.isUploading(false);
        this.setState({ imgIsUploading: false });
        message.error(`${info.file.name} ${messages('components.key400'/*上传失败*/)}`);
      } else if (status === 'removed') {
        result.map((item, index) => {
          if(item.attachmentOID === (info.file.response ? info.file.response.attachmentOID : info.file.attachmentOID)
              || item.attachmentOID === info.file.uid)
            result.splice(index, 1);
        });
        this.setState({ result, imgIsUploading: false },() => {
          this.props.isUploading(false);
          this.props.onChange(result);
        });
      }
    });
  };

  //预览
  handlePreview = (file) => {
    this.state.fileList.map((item, index) => {
      if (item.uid === file.uid) {
        this.setState({
          previewIndex: index,
          previewVisible: true
        })
      }
    })
  };

  render() {
    const { previewVisible, fileList, previewIndex, result } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" style={{ fontSize: 32, color: '#999' }}/>
        <div className="ant-upload-text" style={{ marginTop: 8, color: '#666' }}>{messages('common.upload')/*上传*/}</div>
      </div>
    );
    const uploadOnlyButton = (
      <Button>
        <Icon type="upload" /> {messages('common.upload')/*上传*/}
      </Button>
    );
    const { isExpense } = this.props;
    const upload_headers = {
      'Authorization': 'Bearer ' + this.props.authToken.access_token
    };
    return (
      <div className="image-upload">
        <div className="image-container">
          {isExpense ? <Upload
            name="file"
            data={this.handleData}
            action={this.props.uploadUrl}
            headers={upload_headers}
            // listType="picture-card"
            fileList={fileList}
            showUploadList={{showRemoveIcon: !this.props.disabled}}
            onPreview={this.handlePreview}
            onChange={this.handleChange}
          >
            {(fileList.length >= this.props.maxNum || this.props.disabled) ? null : uploadOnlyButton}
          </Upload> : <Upload
            name="file"
            data={this.handleData}
            action={this.props.uploadUrl}
            headers={upload_headers}
            listType="picture-card"
            fileList={fileList}
            showUploadList={{showRemoveIcon: !this.props.disabled}}
            onPreview={this.handlePreview}
            onChange={this.handleChange}
            accept="image/*"
          >
            {(fileList.length >= this.props.maxNum || this.props.disabled) ? null : uploadButton}
          </Upload>}
        </div>
        {this.props.showMaxNum && !this.props.disabled && (
          <div>({messages('common.max.upload.image', {max: this.props.maxNum})/*最多上传 {max} 张图片*/})</div>
        )}
        {fileList.length > 0 &&
          (isExpense ? <FileViewer
            visible={previewVisible}
            attachments={fileList}
            defaultIndex={previewIndex}
            onCancel={() => this.setState({previewVisible: false, previewIndex: 0})}
            urlKey="fileURL"
            valueKey="attachmentOID"
            result={result}
          /> : <FileViewer
          visible={previewVisible}
          attachments={fileList}
          defaultIndex={previewIndex}
          onCancel={() => this.setState({previewVisible: false, previewIndex: 0})}
        />)
        }
      </div>
    )
  }
}

ImageUpload.propTypes = {
  uploadUrl: React.PropTypes.string,  //上传URL
  attachmentType: React.PropTypes.string.isRequired,  //附件类型
  defaultFileList: React.PropTypes.array,  //默认上传的文件列表
  onChange: React.PropTypes.func,  //上传成功后的回调
  maxNum: React.PropTypes.number,  //最大上传文件的数量
  fileType: React.PropTypes.array,  //上传文件的类型
  fileSize: React.PropTypes.number,  //上传文件的大小
  isShowDefault: React.PropTypes.bool, //是否要进行回显，是否一直允许从父组件接受变化的图片列表
  disabled: React.PropTypes.bool, //是否禁用
  showMaxNum: React.PropTypes.bool, //是否显示最多上传多少图片
  isUploading: React.PropTypes.func, //图片是否在上传中
};

ImageUpload.defaultProps = {
  uploadUrl: `${config.baseUrl}/api/upload/attachment`,
  defaultFileList: [],
  onChange: () => {},
  maxNum: 9,
  isShowDefault:false,
  disabled:false,
  showMaxNum: false,
  isUploading: () => {},
};
function mapStateToProps(state) {
  return {
    authToken: state.main.authToken
  }
}
// 注意
// defaultFileList里面的对象属性要有
//   attachmentOID,
//   fileName,
//   fileURL

export default connect(mapStateToProps)(ImageUpload);
